# -*- coding: utf-8 -*-
from datetime import datetime

from _decimal import Decimal
from flask import Blueprint, render_template, request, jsonify, current_app, redirect, url_for

from application import db
from common.libs.render_helper import getDictFilterField
from web.models.food.Food import Food
from web.models.food.FoodCat import FoodCat
from web.models.food.FoodStockChangeLog import FoodStockChangeLog

route_food = Blueprint('food_page', __name__)


@route_food.route("/index")
def index():
    """查看美食列表"""
    context = {}
    req = request.values  # 取客户端传递过来的查询参数
    query = Food.query
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(Food.status == int(req['status']))
    if 'cat_id' in req and int(req['cat_id']) > 0:
        query = query.filter(Food.cat_id == int(req['cat_id']))
    #  菜单搜索关键字查询...
    food_list = query.order_by(Food.id.desc()).all()
    context['food_list'] = food_list
    context['search_con'] = req
    context['status_mapping'] = current_app.config['STATUS_MAPPING']
    cat_mapping = getDictFilterField(FoodCat, FoodCat.id, "id", [])
    context['cat_mapping'] = cat_mapping
    context['current'] = 'index'
    return render_template("food/index.html", **context)


@route_food.route("/info")
def info():
    """查看美食详情"""
    resp_data = {}
    req = request.args
    id = int(req.get("id", 0))
    reback_url = url_for('food_page.index')
    if id < 1:
        return redirect(reback_url)
    info = Food.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)
    # 查看库存改变情况
    stock_change_list = FoodStockChangeLog.query.filter(FoodStockChangeLog.food_id == id).order_by(
        FoodStockChangeLog.id.desc()).all()
    resp_data['info'] = info
    resp_data['current'] = 'index'
    resp_data['stock_change_list'] = stock_change_list
    return render_template("food/info.html", **resp_data)


@route_food.route("/set", methods=["GET", "POST"])
def set():
    """添加-修改美食"""
    if request.method == "GET":
        resp_data = {}  # 要返回给客户端的数据
        req = request.args
        id = int(req.get('id', 0))
        info = Food.query.filter_by(id=id).first()
        if info and info.status != 1:
            # 当是修改美食，但是处于已删除状态
            return redirect(url_for('food_page.index'))
        # 查询美食分类列表
        cat_list = FoodCat.query.all()
        resp_data['info'] = info
        resp_data['cat_list'] = cat_list  # 美食分类列表
        resp_data['current'] = 'index'  # 当前的选项是index：即美食列表选项
        return render_template("food/set.html", **resp_data)
    elif request.method == "POST":
        # 接收客户端传递过来的post请求参数
        resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
        req = request.values
        id = int(req['id']) if 'id' in req and req['id'] else 0
        cat_id = int(req['cat_id']) if 'cat_id' in req else 0
        name = req['name'] if 'name' in req else ''
        price = req['price'] if 'price' in req else ''
        main_image = req['main_image'] if 'main_image' in req else ''
        summary = req['summary'] if 'summary' in req else ''
        stock = int(req['stock']) if 'stock' in req else ''
        tags = req['tags'] if 'tags' in req else ''

        # 后端验证数据的合法性
        if cat_id < 1:
            resp['code'] = -1
            resp['msg'] = "请选择分类~~"
            return jsonify(resp)
        if name is None or len(name) < 1:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的名称~~"
            return jsonify(resp)
        if not price or len(price) < 1:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的售卖价格~~"
            return jsonify(resp)
        price = Decimal(price).quantize(Decimal('0.00'))
        if price <= 0:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的售卖价格~~"
            return jsonify(resp)
        if main_image is None or len(main_image) < 3:
            resp['code'] = -1
            resp['msg'] = "请上传封面图~~"
            return jsonify(resp)
        if summary is None or len(summary) < 3:
            resp['code'] = -1
            resp['msg'] = "请输入图书描述，并不能少于10个字符~~"
            return jsonify(resp)
        if stock < 1:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的库存量~~"
            return jsonify(resp)
        if tags is None or len(tags) < 1:
            resp['code'] = -1
            resp['msg'] = "请输入标签，便于搜索~~"
            return jsonify(resp)
        # 后台构建美食对象
        food_info = Food.query.filter_by(id=id).first()
        before_stock = 0
        if food_info:
            model_food = food_info
            before_stock = model_food.stock
        else:
            model_food = Food()
            model_food.status = 1
            model_food.created_time = datetime.now()
        # 对美食对象更新数据
        model_food.cat_id = cat_id
        model_food.name = name
        model_food.price = price
        model_food.main_image = main_image
        model_food.summary = summary
        model_food.stock = stock
        model_food.tags = tags
        model_food.updated_time = datetime.now()
        # 更新到数据库中
        db.session.add(model_food)
        db.session.commit()
        return jsonify(resp)
    else:
        return jsonify({'code': -1, 'msg': '请求方式有误~~', 'data': {}})


@route_food.route('/ops', methods=['POST'])
def ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)
    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)
    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "指定美食不存在~~"
        return jsonify(resp)
    # 更新状态，实现软删除与恢复
    if act == "remove":
        food_info.status = 0
    elif act == "recover":
        food_info.status = 1
    food_info.updated_time = datetime.now()
    db.session.add(food_info)
    db.session.commit()
    return jsonify(resp)


@route_food.route("/cat")
def cat():
    """展示美食分类列表"""
    context = {}
    req = request.values
    query = FoodCat.query
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(FoodCat.status == int(req['status']))
    cat_list = query.order_by(FoodCat.weight.desc(), FoodCat.id.desc()).all()
    context = {'cat_list': cat_list}
    context['search_con'] = req  # 返回当前查询的所有参数
    context['status_mapping'] = current_app.config['STATUS_MAPPING']
    context['current'] = 'cat'
    return render_template("food/cat.html", **context)


@route_food.route("/cat-set", methods=["GET", "POST"])
def catSet():
    """添加与修改美食分类"""
    if request.method == "GET":
        resp_data = {}
        req = request.args
        id = int(req.get("id", 0))
        info = None
        if id:  # 是否传id值来区分是 编辑的请求 / 新增请求
            info = FoodCat.query.filter_by(id=id).first()
        resp_data['info'] = info
        resp_data['current'] = 'cat'
        return render_template("food/cat_set.html", **resp_data)
    elif request.method == "POST":
        resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
        req = request.values
        id = req['id'] if 'id' in req else 0
        name = req['name'] if 'name' in req else ''
        weight = int(req['weight']) if ('weight' in req and int(req['weight']) > 0) else 1
        if name is None or len(name) < 1:
            resp['code'] = -1
            resp['msg'] = "请输入符合规范的分类名称~~"
            return jsonify(resp)
        food_cat_info = FoodCat.query.filter_by(id=id).first()
        if food_cat_info:
            # 修改美食分类
            model_food_cat = food_cat_info
        else:
            # 新增美食分类
            model_food_cat = FoodCat()
        model_food_cat.created_time = datetime.now()
        # 不管是新增还是修改， 共同的操作
        model_food_cat.name = name
        model_food_cat.weight = weight
        model_food_cat.updated_time = datetime.now()
        # 提交到数据库中
        db.session.add(model_food_cat)
        db.session.commit()
        return jsonify(resp)
    else:
        return jsonify({'code': -1, 'msg': '请求方式有误~~', 'data': {}})


@route_food.route('/cat-ops', methods=['POST'])
def cat_ops():
    resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values
    # id=4
    id = req['id'] if 'id' in req else 0
    # act=remove
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号~~"
        return jsonify(resp)
    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)
    # 查询数据库获取美食分类对象，且更新状态(软删除、恢复)
    food_cat = FoodCat.query.filter_by(id=id).first()
    if not food_cat:
        resp['code'] = -1
        resp['msg'] = "指定分类不存在~~"
        return jsonify(resp)
    # 更新数据库表 food_cat
    if act == "remove":
        food_cat.status = 0
    elif act == "recover":
        food_cat.status = 1
    else:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)
    food_cat.updated_time = datetime.now()
    # 提交到数据库中
    db.session.add(food_cat)
    db.session.commit()
    # resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    return jsonify(resp)
